import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


/**
 * Class for static DB utilities.
 * @author Jonathan
 *
 */
public class DBUtils {

	public static void setCatalogMaxCard(Map<String, TableData> tempCatalog, long card)
	{
		for(TableData td : tempCatalog.values())
		{
			td.setAttributeMaxCard(card);
		}
	}

	/**
	 * Adds the new table data object to the catalog if the catalog does not contain it already,
	 * otherwise merges the table data with the existing table data in the catalog.
	 * @param catalog
	 * @param table
	 * @param newTd
	 */
	public static void mergeCatalogTableData(
			Map<String, TableData> catalog, String table, TableData newTd)
	{
		TableData td = catalog.get(table);
		if(td == null)
		{
			catalog.put(table, newTd);
		}
		else
		{
			td.joinMerge(newTd);
		}
	}
	
	public static void mergeCatalogs(Map<String, TableData> catalog, Map<String, TableData> updatedCatalog)
	{
		for(Map.Entry<String, TableData> updatedEntry : updatedCatalog.entrySet())
		{
			String table = updatedEntry.getKey();
			TableData updatedTd = updatedEntry.getValue();
			TableData existingTd = catalog.get(table);
			if(existingTd == null)
			{
				catalog.put(table, updatedTd);
			}
			else
			{
				existingTd.joinMerge(updatedTd);
			}
		}
	}
	
	public static ArrayList<Expression> extractReferencedIdentifiers(ArrayList<Expression> selectList, String correlation)
	{
		if(selectList == null || correlation == null)
		{
			return null;
//			throw new RuntimeException("DBUtils.extractReferencedIdentifiers received null input");
		}
		
		// Use Set to prevent duplicates
		Set<Expression> referencedIdentifiers = new HashSet<Expression>();
		
		for(Expression e : selectList)
		{
			ArrayList<Expression> identifiers = e.getIdentifiers();
			if(identifiers != null)
			{
				for(Expression id : identifiers)
				{
					if(id.referencesTable(correlation))
					{
						referencedIdentifiers.add(id);
					}
				}
			}
		}
		
		if(referencedIdentifiers.size() == 0)
		{
			return null;
			//throw new RuntimeException("DBUtils tried to extract attributes for correlation " + correlation + " but found none!");
		}
		
		return new ArrayList<Expression>(referencedIdentifiers);
	}
}
